//app.js
App({
  /**
   * 全局变量
   */
  globalData: {
    btn: false,  //小程序专家申请跳转编辑基本信息带回和上传附件页面刷新导致基本信息清空冲突问题
  },
  api_root: '', // api地址
  siteInfo: require('siteinfo.js'),
  util: require('utils/util.js'),

  /**
   * 生命周期函数--监听小程序初始化
   */
  onLaunch: function() {
    // 设置api地址
    this.setApiRoot();
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })
  },

  //订阅消息
  subscribeMessage: function (tempId) {
    //需要订阅的消息模板，在微信公众平台手动配置获取模板ID
    let message = ''
    let tempIds = []
    tempIds.push(tempId)
    //如果总是拒绝（subscriptionsSetting，2.10.1库才支持）
    if (this.versionCompare('2.10.1')) {
      wx.getSetting({
        withSubscriptions: true,//是否同时获取用户订阅消息的订阅状态，默认不获取
        success: (res) => {
         // console.log("11",res.subscriptionsSetting.itemSettings)
          if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
            res.subscriptionsSetting.itemSettings[tempId] == "reject") {
            //打开设置去设置
            this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
          } else {
            wx.requestSubscribeMessage({
              tmplIds: tempIds,
              success: (res) => {
                if (res[message] == 'accept') {
                  //用户允许
                }
              },
              fail: (res) => { console.info(res) },
            })
          }
        }
      })
    } else if (this.versionCompare('2.4.4')) {
      wx.requestSubscribeMessage({
        tmplIds: tempIds,
        success: (res) => {
          if (res[message] == 'accept') {
            //用户允许
          }
        },
        fail: (res) => { console.info(res) },
      })
    }
  },
  //打开设置
  openConfirm: function (message) {
    wx.showModal({
      content: message,
      confirmText: "确认",
      cancelText: "取消",
      success: (res) => {
        //点击“确认”时打开设置页面
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              // console.log(res.authSetting)
            },
            fail: (error) => {
              console.log(error)
            }
          })
        } else {
          console.log('用户点击取消')
        }
      }
    });
  },
  //基础库版本比较
  versionCompare: function (v) {
    const version = wx.getSystemInfoSync().SDKVersion
   // console.log("v", v)
   // console.log("version", version)
    if (this.util.compareVersion(version, v) >= 0) {
      return true
    } else {
      return false
    }
  },

  /**
   * 设置api地址
   */
  setApiRoot: function() {
    this.api_root = this.siteInfo.siteroot;
  },

  /**
   * 获取小程序基础信息
   */
  getWxappBase: function(callback) {
//    console.log("获取小程序基础信息");
    // let App = this;
    // App._get('wxapp/base', {}, function (result) {
    //   // 记录小程序基础信息
    //   wx.setStorageSync('wxapp', result.data.wxapp);
    //   callback && callback(result.data.wxapp);
    // }, false, false);
  },
  /**
   * 执行用户登录
   */
  doLogin: function() {
    var _this = this
    //检查登录状态是否过期
    wx.checkSession({
      success(res) {
        //console.log("Session失效")
      },
      fail() {
        console.log("Session失效")
      }
    })
    wx.login({
      success: function (res) {
        wx.setStorageSync('code', res.code)
      }
    });
    // 保存当前页面
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/loginway/loginway" != currentPage.route &&
        wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/loginway/loginway"
    });
  },

  /**
   * 当前用户id
   */
  getUserId: function() {
    return this.globalData.userId;
  },

  /**
   * 显示成功提示框
   */
  showSuccess: function(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: 1000,
      success: function() {
        callback && (setTimeout(function() {
          callback();
        }, 1500));
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showError: function(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        // callback && (setTimeout(function() {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },

  /**
   * 微信uploadFile请求-文件上传都需要登录
   */
  _uploadFile: function(url, filePath, name, formData, success, fail, complete) {
    wx.showNavigationBarLoading();
    wx.showLoading();
    let _this = this;
    let token = wx.getStorageSync('token');
    var requestHead = {
      'content-type': 'multipart/form-data'
    }
    if ('' !== token && null !== token && undefined !== token) {
      requestHead = {
        'content-type': 'multipart/form-data',
        'Authorization': token
      }
    }
    wx.uploadFile({
      url: url,
      header: requestHead,
      filePath: filePath,
      name: name,
      formData: formData,
      success(res) {
        // console.log("res", res);
        const strToObj = JSON.parse(res.data);
        // if (res.statusCode === 401 || res.statusCode === '401') {
        //   _this.doLogin();
        // }
        if (strToObj.code === 0 || strToObj.code === '0') {
          success && success(strToObj);
          // _this.showSuccess('提交成功')
        } else if (strToObj.code === 10000 || strToObj.code === '10000') {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          _this.doLogin();
        } else if (strToObj.code === 40013 || strToObj.code === '40013') {
          success && success(strToObj);
        }  else {
          _this.showError(strToObj.msg);
          return false;
        }
        
      },
      fail: function(res) {
        _this.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        complete && complete(res);
      },
    });
  },
  /**
   * get请求
   */
  _get: function(url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();
    wx.showLoading();
    let _this = this;
    // 构造get请求
    let request = function() {
      let token = wx.getStorageSync('token');
      var requestHead = {
        'content-type': 'application/json'
      }
      wx.request({
        url: url,
        header: requestHead,
        data: data,
        success: function(res) {
          // console.log(res);
          if (res.data.code === 0 || res.data.code === '0') {
            success && success(res.data);
          } else if (res.data.code === 10000 || res.data.code === '10000') {
            // 登录态失效, 重新登录
            wx.hideNavigationBarLoading();
            _this.doLogin();
          } else {
            _this.showError(res.data.msg);
            return false;
          }
        },
        fail: function(res) {
          _this.showError(res.errMsg, function() {
            fail && fail(res);
          });
        },
        complete: function(res) {
          wx.hideLoading();
          wx.hideNavigationBarLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? _this.doLogin(request) : request();
  },

  /**
 * getLogin需要登录的get请求
 */
  _getLogin: function (url, data, success, fail, complete, check_login) {
    wx.showNavigationBarLoading();
    wx.showLoading();
    let _this = this;
    // 构造get请求
    let request = function () {
      let token = wx.getStorageSync('token');
      var requestHead = {
        'content-type': 'application/json'
      }
      if ('' !== token && null !== token && undefined !== token) {
        requestHead = {
          'content-type': 'application/json',
          'Authorization': token
        }
      }
      wx.request({
        url: url,
        header: requestHead,
        data: data,
        success: function (res) {
          //  console.log(res);
          if (res.statusCode === 401 || res.statusCode === '401') {
            _this.doLogin();
          }
          if (res.data.code === 0 || res.data.code === '0') {
            success && success(res.data);
          } else if (res.data.code === 10000 || res.data.code === '10000') {
            // 登录态失效, 重新登录
            wx.hideNavigationBarLoading();
            wx.hideLoading()
            _this.doLogin();
          } else {
            _this.showError(res.data.msg);
            return false;
          }
        },
        fail: function (res) {
          _this.showError(res.errMsg, function () {
            fail && fail(res);
          });
        },
        complete: function (res) {
          wx.hideNavigationBarLoading();
          wx.hideLoading();
          complete && complete(res);
        },
      });
    };
    // 判断是否需要验证登录
    check_login ? _this.doLogin(request) : request();
  },

  /**
   * post提交
   */
  _post_form: function(url, data, success, fail, complete) {
    wx.showNavigationBarLoading();
    wx.showLoading();
    let _this = this;
    let token = wx.getStorageSync('token');
    if (url == "user/login") {
      token = null;
    }
    var requestHead = {
      'content-type': 'application/x-www-form-urlencoded'
    }
    if ('' !== token && null !== token && undefined !== token ) {
      requestHead = {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': token
      }
    }
    wx.request({
      url: url,
      header: requestHead,
      method: 'POST',
      data: data,
      success: function(res) {
        //console.log(res);
        // if (res.statusCode === 405) {
        //   if (res.data.code === 0 || res.data.code === '0') {
        //     success && success(res.data);
        //     if (res.data.data.site != undefined) {
        //       global.siteName = res.data.data.site.name
        //     }
        //   } else {
        //     // 登录态失效, 重新登录
        //     wx.hideNavigationBarLoading();
        //     App.doLogin();
        //     return false;
        //   }
        // } else if (res.statusCode !== 200 || typeof res.data !== 'object') {
        //   App.showError('网络请求出错');
        //   return false;
        // }
        if (res.data.code === 0 || res.data.code === '0') {
          success && success(res.data);
        } else if (res.data.code === 10000 || res.data.code === '10000') {
          // 登录态失效, 重新登录
          _this.doLogin(function() {
            _this._post_form(url, data, success, fail);
          });
          return false;
        } else if (res.data.code === 10018 || res.data.code === "10018") {
          success && success(res.data);
        } else if (res.data.code === 40013 || res.data.code === "40013") {
          success && success(res.data);
        }else {
          _this.showError(res.data.msg, function() {
            fail && fail(res);
          });
          return false;
        }
      },
      fail: function(res) {
        // console.log(res);
        _this.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        complete && complete(res);
      }
    });
  },
  
  /**
   * 验证是否存在user_info
   */
  validateUserInfo: function() {
    let user_info = wx.getStorageSync('user_info');
    return !!wx.getStorageSync('user_info');
  },

  /**
   * 对象转URL
   */
  urlEncode: function urlencode(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(function(_value) {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },

  /**
  * 对象转URL
  */
  myUrlEncode: function urlencode(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (null !== value) {
        if (value.constructor == Array) {
          value.forEach(function (_value) {
            _result.push(key + "~" + _value);
          });
        } else {
          _result.push(key + '~' + value);
        }
      }
    }
    return _result.join('#');
  },
})